<template>
  <!--  定价曲线匹配规则模板 -->
  <div>
    <!-- 按钮与搜索 -->
    <el-row class="curveRule container">
      <el-col style="margin-right: 10px" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          v-if="templateId"
          exportIcon
          importIcon
          :configIcon="false"
          @search="(searchForm.page = 1), searchFunc()"
          @clear="
            (searchForm.curveRuleCode = ''),
            (searchForm.effectDate = ''),
            (searchForm.invalidDate = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea" v-if="templateId">
            <el-button @click="addOrEditFunc('1')">新增</el-button>
            <el-button @click="addOrEditFunc('2')">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
            <el-button @click="addOrEditFunc('3')">查看</el-button>
            <el-button @click="addOrEditFunc('4')">查看历史</el-button>
          </template>

           <div slot="exportArea">
                  <!-- 导出操作区域 -->
              <el-button @click="exportExcel('1')"
              >导出模板</el-button>
              <el-button @click="exportExcel('2')"
              >导出数据</el-button> 
         </div>
          <!-- 导入 -->
          <div slot="importArea">
                  <!-- 导入操作区域 -->
                  <el-upload
                    accept=".xls, .xlsx"
                    ref="upload"
                    :multiple="false"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    action
                    :limit="1"
                    :http-request="uploadFile"
                  >
                    <el-button>导入</el-button>
                  </el-upload>
          </div>

          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="107px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="规则编号：">
                <el-input
                  v-model="searchForm.curveRuleCode"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="生效日期：">
                <el-date-picker
                  v-model="searchForm.effectDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  style="width: 150px"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="截止日期：">
                <el-date-picker
                  v-model="searchForm.invalidDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  style="width: 150px"
                ></el-date-picker>
              </el-form-item>
            </el-form>
          </template>
        </upper-template>
        <!-- 列表 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
          v-if="templateId"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="curveRuleCode"
            label="规则编号"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            v-for="(value, key) in this.headData"
            :key="key"
            :prop="key"
            :label="value.elementFieldName"
            :formatter="getDynamicValue"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="curveId"
            label="定价曲线"
            :show-overflow-tooltip="true"
            :formatter="formatFtpCurveId"
          ></el-table-column>
          <el-table-column
            prop="effectDate"
            :show-overflow-tooltip="true"
            label="生效日期"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.effectDate">
                {{ timeFormatShort(scope.row.effectDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="invalidDate"
            :show-overflow-tooltip="true"
            label="生效截止日"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.invalidDate">
                {{ timeFormatShort(scope.row.invalidDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="createdTm"
            :show-overflow-tooltip="true"
            label="创建时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            :show-overflow-tooltip="true"
            label="修改人"
            sortable
            :formatter="(row) => row.modifier || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            :show-overflow-tooltip="true"
            label="修改时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.modifiedTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="templateId"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 新增、编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="titleName"
      :visible.sync="curveRuleAddAndEditDi"
      width="45%"
      top="2%"
    >
      <el-form
        :model="saveRuleForm"
        ref="saveRuleForm"
        label-width="120px"
        label-position="right"
        :rules="saveRuleFormRules"
      >
        <el-row>
          <el-col :span="15">
            <el-form-item label="规则编号：" prop="curveRuleCode">
              <el-input
                v-model.trim="saveRuleForm.curveRuleCode"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              >（提示：只能输入字母、数字及下划线，最长字符数为40位）</el-form-item
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="生效日期：" prop="effectDate">
              <el-date-picker
                v-model="saveRuleForm.effectDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="生效截止日：" prop="invalidDate">
              <el-date-picker
                v-model="saveRuleForm.invalidDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="规则模板：">{{ ruleGroupName }}</el-form-item>
          </el-col>
        </el-row>
        <!-- 循环展示字段 -->
        <el-row v-for="(value, key) in this.headData" :key="key">
          <el-col :span="15">
            <dynamicForm :dataOriginProps="value" :key="key"></dynamicForm>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="定价曲线：" prop="curveId">
              <el-select
                v-model="saveRuleForm.curveId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in curveIds"
                  :key="item.curveCode"
                  :label="item.curveName"
                  :value="item.curveCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
         
      </el-form>
      <div slot="footer" v-if="ruleOperateType != '3'">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="curveRuleAddAndEditDi = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增、编辑弹窗 -->  
    <!-- 查看历史弹窗 -->
    <el-dialog
      v-dialogDrag
      title="历史信息查询页面"
      :visible.sync="historyVisible"
      width="60%"
      top="2%"
    >
      <historyTable
        :tableData="tableDataH"
        :headData="headDataH"
        :total="totalH"
        @handleSizeChange="handleSizeChangeH"
        @handleCurrentChange="handleCurrentChangeH"
        @searchFunc="getTableDataHistory"
      ></historyTable>
    </el-dialog>
    <!-- 查看历史弹窗 -->
  </div>
</template>

<script>
import { ruleTemplate,curveRule,publicManage_pub } from "@/api/index";
import { getDict } from "@/api/getDict";
import moment from "moment";
import dynamicForm from "../methodRule/components/dynamicForm";
import historyTable from "../methodRule/components/historyTable";
export default {
  //定义数据
  data() {
    return { 
      toFormData:[], // 回显的数据
      curveRuleId: "",
      searchForm: {
        page: 1,
        size: 15,
      },
      ruleOperateType: "",
      total: 0,
      titleName: "",
      curveRuleDi: false,
      headData: {},
      tableData: [],
      curveRuleAddAndEditDi: false,
      saveRuleForm: {
        curveId: "",
        effectDate: "",
        invalidDate: "",
        curveRuleId: "",
        curveRuleCode:"",
        ruleDatas: [],
        ruleStatus:"1"
      },
      //定价曲线数组
      curveIds: [],
      //表单字段规则校验
      saveRuleFormRules: {
        curveRuleCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]{1,40}$/,
            message: "只可输入(1-40)位的英文字母、数字和下划线！",
            trigger: "blur",
          }
        ],
        effectDate: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { validator: this.invalidDateFun, trigger: "blur" }
        ],
        invalidDate: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        curveId: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ] 
      },
       
      //是否数组
      booleanFlags: [],
      //列表标识
      rightListFlag: false,
      //待修改规则数据集合
      ruleDatas: [],
      
      //动态表单悬浮框
      elementFieldContent: false,
      //查询历史弹窗
      historyVisible: false,
      tableDataH: [],
      headDataH: {},
      rowHistory: {},
      pageH: 1,
      sizeH: 15,
      totalH: 0,
    };
  },
  props: {
    templateId: {
      type: String,
      default: "",
    },
    curveRuleGroup: {
      type: String,
      default: "",
    },
    ruleGroupName: {
      type: String,
      default: "",
    },
  },
  //组件引入
  components: {
    dynamicForm,
    historyTable,
  },
  //创建初始化
  created() {
    this.curveIdsInit();//曲线接口
  },
  mounted() {},
  //监控数值变化
  watch: {
    templateId: function (newVal) {
      this.templateId = newVal;
      this.searchForm.page = 1;
      this.searchForm.size = 15
    },
    curveRuleGroup: function (newVal) {
      this.curveRuleGroup = newVal;
    },
    ruleGroupName: function (newVal) {
      this.ruleGroupName = newVal;
    },
  },
  //运算
  computed: {},
  methods: {
    //格式化
    datetimeFormatter(rows) {
      let str = "";
      switch (this.getTimeTypeQueen(rows.term)) {
        case "Y":
          str = this.getTimeTypeFront(rows.term) + "年";
          break;
        case "M":
          str = this.getTimeTypeFront(rows.term) + "月";
          break;
        case "D":
          str = this.getTimeTypeFront(rows.term) + "天";
          break;
        default:
          break;
      }
      return str;
    },
     getTimeTypeQueen(val) {
      return val.slice(-1);
    },
      getTimeTypeFront(val) {
      return val.slice(0, -1);
    },
    // 删除
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = { ids: selection.map((v) => v.curveRuleId) };
          curveRule.remove(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
   
    //保存
    saveFunc() {
      this.$refs["saveRuleForm"].validate((valid) => {
        if (valid) {
          let ruleDatas = [];
          for (var keyHeadData in this.headData) {
            let ruleValue = this.headData[keyHeadData][keyHeadData];
            if(this.headData[keyHeadData].elementDataMap.elementType=='5'){
              ruleValue = this.headData[keyHeadData][keyHeadData+'L']+this.headData[keyHeadData][keyHeadData+'R'];
            } 
            let map = {
              templateFieldId: keyHeadData,
              ruleValue: ruleValue,
            };
            ruleDatas.push(map);
          }
          this.saveRuleForm.ruleDatas = ruleDatas;
          this.saveRuleForm.template = {
            templateId:this.templateId
          }
          this.saveRuleForm.curveRuleGroup = {
            curveRuleGroup: this.curveRuleGroup,
            ruleGroupName: this.ruleGroupName,
          };
          let data = {
            operateType: this.ruleOperateType,
            curveRule: { ...this.saveRuleForm },
          };
          curveRule.save(data).then((res) => {
            if (res.code === 200) {
              this.curveRuleAddAndEditDi = false;
              this.$message.success("保存成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });   
        } else {
          this.$message.warning("请填写正确的信息！");
        }
      });
    },
    //新增、编辑弹窗
    addOrEditFunc(val) {
      this.ruleOperateType = val;
      
      if (this.ruleOperateType === "1") {
        if (this.templateId == "") {
          this.$message.warning("请在左侧选择模板");
          return;
        }
        this.titleName = "新增定价曲线匹配规则信息";
        this.curveRuleAddAndEditDi = true;
        this.$nextTick(() => {
        //清除校验结果
        this.$refs.saveRuleForm.clearValidate();
      });
        //清空表单
        this.emptydataTableForm();
      } else if (this.ruleOperateType === "2" || this.ruleOperateType === "3" ) {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else {
          // 调用toForm回显接口
          this.getcurveRuleToForm()
          this.titleName = this.ruleOperateType == '2'? "编辑定价曲线匹配规则信息":"查看定价曲线匹配规则信息";
          this.curveRuleAddAndEditDi = true;
          // 清除不必要的保存数据
          for (let keyHeadData in this.headData) {
              delete this.saveRuleForm[keyHeadData]
          }
          this.saveRuleForm = Object.assign({},this.saveRuleForm,selection[0]) 
        }
      } else if (this.ruleOperateType === "4") {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else {
          //查看历史页面
          this.historyVisible = true;
          this.rowHistory = selection[0];
          // 获取历史页面数据
          this.getTableDataHistory();
        }
      }
    },
    // 获取回显数据
    getcurveRuleToForm() {
      this.curveRuleId = ""
      let selection = this.$refs.multipleTable.selection;
      //新增
      if(this.ruleOperateType == '2' || this.ruleOperateType == '3'){
        if(selection.length !="1"){
          this.$message.warning("请选择一条数据")
          return
        }
       this.curveRuleId = selection[0].curveRuleId
      
        let params = {
          curveRuleId: this.curveRuleId,
          templateId: this.templateId
        }
        curveRule.toForm(params)
        .then((res) => {
          if (res.code === 200) {
            this.toFormData = res.datas[0]
            for(let i = 0;i<this.toFormData.length;i++){
              for(let val in this.headData){
                if(this.toFormData[i].key == val){
                  let code = this.toFormData[i].value;
                 
                  if(this.headData[val].elementDataMap.elementType=='5'){
                    this.$set(this.headData[val],this.headData[val].templateFieldId+'L', code.substr(0,code.length - 1));
                    this.$set(this.headData[val],this.headData[val].templateFieldId+'R', code.substr(code.length - 1,1));
                  } else {
                    this.$set(this.headData[val],this.headData[val].templateFieldId,code);
                  }
                  this.$set(this.headData[val],this.headData[val].templateFieldIdName,this.toFormData[i].valueName)
                }
              }
            }
            
          }
        });
      }  
    },
    emptydataTableForm() {
      this.saveRuleForm.curveId = "";
      this.saveRuleForm.effectDate = "";
      this.saveRuleForm.invalidDate = "";
      this.saveRuleForm.curveRuleId = "";
      this.saveRuleForm.curveRuleCode = "";
      this.saveRuleForm.ruleDatas = [];
    },
    
    getTableDataHistory() {
      let params = {
        curveRuleCode: this.rowHistory.curveRuleCode,
        page: this.pageH,
        ruleStatus: '0',
        size: this.sizeH,
        templateId: this.rowHistory.templateId,
      };
      curveRule.findHistory(params).then((res) => {
        if (res.code == 200) {
          this.headDataH = res.datas.fieldsAndTitles;
          //规则编号转化：breakRuleCode-->methodRuleCode
          for(let i = 0;i<res.datas.rows.length;i++){
              res.datas.rows[i].methodRuleCode = res.datas.rows[i].curveRuleCode;
          }
          this.tableDataH = res.datas.rows;
          this.totalH = res.datas.total;
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    //定价曲线数组初始化
    curveIdsInit() {
      publicManage_pub.curveDataGetCurveList().then((res) => {
        if (res.code === 200) {
          this.curveIds = res.datas;
        }
      });
    },
    formatFtpCurveId(row){
      let obj = this.curveIds.filter(function (c) {
          if (c.curveCode == row.curveId) {
              return c
          }
      })
      return obj[0].curveName;
    },


     
    //获取字典数据
    getDictData(val) {
      ruleTemplate.curveRuleFindAll({ templateFieldId: val }).then((res) => {
        if (res.code === 200) {
          let result = res.datas;
          getDict(result.data).then((res) => {
            if (res.code == 200) {
              return res.datas;
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    //   点击行选中
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
     
    //查询数据
    searchFunc() {
      this.rightListFlag = true;
      this.searchForm.templateId = this.templateId;
      this.searchForm.curveRuleGroup = this.curveRuleGroup;
      ruleTemplate
        .findFieldListByTemplateId({ templateId: this.templateId })
        .then((res) => {
          if (res.code === 200) {
            this.headData = res.datas.fieldValues;
          }
          curveRule.findAll(this.searchForm).then((res) => {
            if (res.code == 200) {
              this.tableData = res.datas.rows;
              this.total = res.datas.total;
            }
          });
        });
    },

       
    //列表动态数据赋值
    getDynamicValue(row, column) {
      let columnId = column.property;
      let data = row.ruleDatas;
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].templateFieldId == columnId) {
            // return data[i].ruleValue;
            return row[columnId];
          }
        }
      }
    },
     
    //事件转换
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    timeFormatShort(val) {
      if (val) return moment(val).format("YYYY-MM-DD");
      else return "";
    },
    //页码值改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    //页码值改变
    handleSizeChangeH(val) {
      this.sizeH = val;
      this.getTableDataHistory();
    },
    //当前页改变
    handleCurrentChangeH(val) {
      this.pageH = val;
      console.log(`当前页: ${val}`);
      this.getTableDataHistory();
    },
    invalidDateFun(rule, value, callback){
    	var effectDate = this.saveRuleForm.effectDate;
      var date1 = new Date(Date.parse(effectDate.replace("-","/")));
      var date2 = new Date(Date.parse(value.replace("-","/")));
		
        if (date1 > date2) {
        	return callback(new Error("生效截止日必须大于等于生效日期!"));
        } else callback();
    },
    //导出文件
    exportExcel(tmpFlag) {

       if(this.templateId==''){
        this.$message.success("请先选择一条数据，再进行点击下载!");
      } else {
        let selection = this.$refs.multipleTable.selection;

        let param = {
          hasTemplete: tmpFlag, //1为导出模板
          curveRuleCode: this.searchForm.curveRuleCode,  
          effectDate: this.searchForm.effectDate,
          invalidDate: this.searchForm.invalidDate,
          templateId: this.templateId,
          curveRuleGroup: this.curveRuleGroup,
          selectedData: selection.map((v) => v.curveRuleId)
        };

        curveRule
        .exp(param)
        .then((res) => {
          if (res) {
            var filename = decodeURI(res.headers["content-disposition"]).split("=")[1];
            let contenttype =
              filename.substring(filename.lastIndexOf("."), filename.length) === "xlsx"
                ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
                : "application/vnd.ms-excel;charset=utf-8";
            const content = res.data;
            const blob = new Blob([content], {
              type: contenttype,
            });
            let url = window.URL.createObjectURL(blob);
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", filename);
            document.body.appendChild(link);
            link.click();
          }
        })
        .catch(function (error) {
          console.log(error);
          // this.$message.error("导出失败！");
        });
      }
    },
     // 上传文件之前的钩子
    beforeUpload(file) {
      let name = file.name;
      let type = name.substring(name.lastIndexOf("."), name.length);
      if (type === ".xls" || type === ".xlsx") {
        return true;
      } else {
        this.$message.warning("只能选择xls或者xlsx格式的文件上传");
        return false;
      }
    },
     // 上传文件
    uploadFile(item) {
      let form = new FormData();
      // 文件对象
      form.append("excelFile", item.file);
      // 发送请求
      curveRule.imp(form)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("导入成功");
            this.searchFunc();
          } else {
            this.$message.error(res.message);
          }
          this.$refs.upload.clearFiles();
        })
        .catch((err) => {
          this.$refs.upload.clearFiles();
        });
    },


  }
};
</script>


<style lang="scss" scoped>
.buessinessEleTable .el-table__header th {
  /deep/ .cell {
    white-space: nowrap !important;
  }
}

/deep/.el-dialog__body {
  max-height: 400px;
}
.tipMessage {
  line-height: 32px;
  margin-left: 5px;
  color: red;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500 !important;
  font-size: 12px !important;
}
.selectBox {
  background: url("~@/assets/images/select_btn.gif");
  background-repeat: no-repeat;
  height: 26px;
  width: 23px;
  position: absolute;
  right: 0;
  top: 5px;
  cursor: pointer;
}
/depp/.el-popover {
  max-height: 160px;
  overflow: auto;
}
</style>

